package group

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"go-admin/base/dao"

	"go-admin/base/internal/svc"
	"go-admin/base/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateLogic) Update(req *types.GroupUpdateReqDTO) (resp *types.GroupBooleanRespDTOS, err error) {
	// todo: add your logic here and delete this line
	group, err := l.svcCtx.GroupModel.FindByName(l.ctx, req.Name)
	if err != nil {
		if err != sqlc.ErrNotFound {
			_ = fmt.Errorf(err.Error())
			return nil, err
		}
	}
	if group.Id != req.Id {
		fmt.Errorf(err.Error())
		return nil, err
	}
	l.svcCtx.GroupModel.Update(l.ctx, &dao.Group{
		Id: req.Id,
		Name: sql.NullString{
			String: req.Name,
			Valid:  true,
		},
		NickName: sql.NullString{
			String: req.NickName,
			Valid:  true,
		},
		Description: sql.NullString{
			String: req.Description,
			Valid:  true,
		},
	})

	return &types.GroupBooleanRespDTOS{
		Data: true,
		Result: types.Result{
			Code: 200,
		},
	}, nil
}
